﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Portal.Core;
using Portal.Core.Helper;
using Portal.Core.Web.UI;
using Portal.Data;
using Portal.Data.Entity;
using Portal.Data.Security;
using Page = System.Web.UI.Page;

public partial class Admin_MasterCreate : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //check is access
            if (PortalContext.CurrentUser != null)
                LoadDefault();
            else
                Response.Redirect(CoreContext.basepath + "admin_login.aspx");
        }
    }

    private void LoadDefault()
    {
        //template
        object listcats = Category.ListAll();
        object listsinglepage = WebpartPage.ListNormalPages();

        Cat1From.DataSource = listcats;
        Cat1From.DataBind();

        Cat1To.DataSource = listcats;
        Cat1To.DataBind();
        WebPage1To.DataSource = listsinglepage;
        WebPage1To.DataBind();

        Cat2from.DataSource = listcats;
        Cat2from.DataBind();

        Cat2To.DataSource = listcats;
        Cat2To.DataBind();

        WebPage2To.DataSource = listsinglepage;
        WebPage2To.DataBind();
    }

    protected void btnSubmit1_Click(object sender, EventArgs e)
    {
        Category temp = Category.FindByPrimaryKey(Cat1From.SelectedValue);
        WebpartPage listTemp = WebpartPage.FindByPrimaryKey(temp.ListPage_ID);
        WebpartPage detailTemp = WebpartPage.FindByPrimaryKey(temp.DetailPage_ID);
        //for category
        foreach (ListItem item in Cat1To.Items)
        {
            if (item.Selected)
            {
                Category catToset = Category.FindByPrimaryKey(item.Value);
                WebpartPage listToset = WebpartPage.FindByPrimaryKey(catToset.ListPage_ID);
                WebpartPage detailToset = WebpartPage.FindByPrimaryKey(catToset.DetailPage_ID);
                CopyPage(listTemp, listToset, catToset.Name, ObjectWebPartPageType.WebPartPageType.System);
                CopyPage(detailTemp, detailToset, catToset.Name, ObjectWebPartPageType.WebPartPageType.System);
            }
        }

        //for web page (single page)
        foreach (ListItem item in WebPage1To.Items)
        {
            if (item.Selected)
            {
                CopyPage(listTemp, WebpartPage.FindByPrimaryKey(item.Value), item.Text, ObjectWebPartPageType.WebPartPageType.Normal);
            }
        }
    }

    private void CopyPage(WebpartPage template, WebpartPage pageSet, string catName, ObjectWebPartPageType.WebPartPageType pagetype)
    {
        if (string.IsNullOrEmpty(pageSet.Name))
            pageSet.Name = catName + pageSet.ID;
        if (string.IsNullOrEmpty(pageSet.Title))
            pageSet.Title = catName + pageSet.ID;
        pageSet.Layout_ID = template.Layout().ID;
        pageSet.PageType = (int)pagetype;
        pageSet.Update();

        //Delete old webparts
        Webpart.RemoveFromWebpartPage(pageSet.ID);

        IList wpInTemplate = Webpart.FindByWebpartPage(template.ID);
        foreach (Webpart wp in wpInTemplate)
        {
            var tempwp = new Webpart
                             {
                                 Definition_ID = wp.Definition().ID,
                                 Page_ID = pageSet.ID,
                                 WebPartOrder = wp.WebPartOrder,
                                 Zone = wp.Zone
                             };
            tempwp.SetConfig(wp.GetConfig());
            tempwp.SaveWithoutPermission();
        }
    }

    protected void btnPick2_Click(object sender, EventArgs e)
    {
        //Duyệt các module trong mục chọn này
        LoadWebparts();
    }

    protected void btnSubmit2_Click(object sender, EventArgs e)
    {
        foreach (ListItem iwp in listWebparst.Items)
        {
            if (iwp.Selected)
            {
                Webpart wp = Webpart.FindByPrimaryKey(Convert.ToInt32(iwp.Value));

                //sao chép webpart đã chọn vào trang đích

                //doing with category
                foreach (ListItem icat in Cat2To.Items)
                {
                    if (icat.Selected)
                    {
                        Category cat = Category.FindByPrimaryKey(icat.Value);
                        WebpartPage listToset = WebpartPage.FindByPrimaryKey(cat.ListPage_ID);
                        WebpartPage detailToset = WebpartPage.FindByPrimaryKey(cat.DetailPage_ID);

                        //tim kiểu trang (hiển thị/Chi tiết)
                        if (WppTo.SelectedValue == "-1" || WppTo.SelectedValue == "0")
                            AddWebpart(wp, listToset, cat.Name);
                        if (WppTo.SelectedValue == "-1" || WppTo.SelectedValue == "1")
                            AddWebpart(wp, detailToset, cat.Name);
                    }
                }

                //doing with WebPage
                foreach (ListItem item in WebPage2To.Items)
                {
                    if (item.Selected)
                    {
                        AddWebpart(wp, WebpartPage.FindByPrimaryKey(item.Value), item.Text);
                    }
                }
            }
        }
    }

    private void AddWebpart(Webpart wpinput, WebpartPage wpp, string sCatName)
    {
        var wp = MakeWebpart(wpinput, wpp);

        if (string.IsNullOrEmpty(wpp.Name))
        {
            wpp.Name = sCatName + wpp.ID.ToString();
            wpp.Title = sCatName + wpp.ID.ToString();
        }
        //Load layout của trang gốc, nếu chọn
        if (cbSetLayout.Checked)
        {
            wpp.ChangeLayout(Convert.ToInt32(hdLayoutIDparent.Value));
        }

        //Tìm vị trí Zone thích hợp để thêm vào        
        string newzone = wpp.Layout().DefaultZone;

        IList list = ((WebLayout)Page.LoadControl("~/" + wpp.Layout().Path)).allZones();
        foreach (string zone in list)
        {
            if (wp.Zone.Equals(zone, StringComparison.OrdinalIgnoreCase))
            {
                newzone = zone;
                if (cbDeleteOld.Checked) //kiểm tra xem có Wp nào giống nó ở cùng vị trí đã có sẵn ko? -> để xóa
                {
                    IList listDelWp = Webpart.ListByZonePageDef(zone, wpp.ID, wp.Definition().ID);
                    if (listDelWp.Count > 0)
                    {
                        foreach (Webpart wpdel in listDelWp)
                        {
                            wp.WebPartOrder = wpdel.WebPartOrder; //lấy vị trí của thằng cũ
                            wpdel.Delete();
                        }
                    }
                }
                break;
            }
        }
        wp.Zone = newzone;
        wp.Save();
    }

    private Webpart MakeWebpart(Webpart wp, WebpartPage wpp)
    {
        var newwp = new Webpart
                            {
                                Definition_ID = wp.Definition().ID,
                                Page_ID = wpp.ID,
                                Properties = wp.Properties,
                                WebPartOrder = wp.WebPartOrder,
                                Zone = wp.Zone
                            };
        newwp.SetConfig(wp.GetConfig());
        return newwp;
    }

    protected void btnDeleteWp_Click(object sender, EventArgs e)
    {
        foreach (ListItem iwp in listWebparst.Items)
        {
            if (iwp.Selected)
            {
                Webpart wp = Webpart.FindByPrimaryKey(Convert.ToInt32(iwp.Value));
                wp.Delete();
            }
        }
        LoadWebparts();
    }

    private void LoadWebparts()
    {
        //Duyệt các module trong mục chọn này
        var catfrom = Category.FindByPrimaryKey(Cat2from.SelectedValue);
        int wppId = ddlWpp.SelectedValue.Equals("0") ?
            catfrom.ListPage_ID : catfrom.DetailPage_ID;

        var wpp = WebpartPage.FindByPrimaryKey(wppId);

        hdLayoutIDparent.Value = wpp.Layout().ID.ToString();

        listWebparst.DataSource = WebpartItem.Gets(wppId);
        listWebparst.DataBind();
    }

    public class WebpartItem
    {
        private const string Key = "WebpartItemList";
        public int Id { get; set; }
        public string Name { get; set; }
        public static List<WebpartItem> Gets(int wppId)
        {
            var obj = CacheHelper.Instance.Get(Key + wppId);
            if (obj != null)
                return (List<WebpartItem>)obj;

            var webparts = Webpart.FindByWebpartPage(wppId);
            var results = webparts.Select(wp => new WebpartItem { Id = wp.ID, Name = wp.DisplayName() }).ToList();
            CacheHelper.Instance.Set(Key + wppId, results);
            return results;
        }
    }
}